package hk.com.fgoproduction.getdroplets.Activity

import android.app.AlertDialog
import android.os.Bundle
import android.widget.ListView
import hk.com.fgoproduction.getdroplets.DropboxAPI.AFile
import hk.com.fgoproduction.getdroplets.Lib.Common.ThisApplication
import hk.com.fgoproduction.getdroplets.Lib.Common.ToolInstance.LogInstance
import hk.com.fgoproduction.getdroplets.Lib.FileMan.FileMan
import hk.com.fgoproduction.getdroplets.Lib.FileMan.FileManActFrame
import hk.com.fgoproduction.getdroplets.R
import kotlinx.android.synthetic.main.file_man_view.*
import org.jetbrains.anko.onClick
import org.jetbrains.anko.toast
import java.io.File
import java.util.*

/***
 * View file_man_view controller(ListActivity)
 * For tree view, refer TreeTestActivity
 */
class LocalFileManActivity : FileManActFrame(), ThisApplication.BgThreadCallback {

    private val MAP_TAG_ITEM = "item"
    private val MAP_TAG_PATH = "path"
    override val showLog = true

    private val fMan = FileMan()
    private lateinit var obj: AFile

    override var currentPath = FileMan.ROOT
    override var ROOT = FileMan.ROOT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val checkList: ShortArray? = savedInstanceState?.getShortArray("checkList")

        initView()
        initVar()
        restoreState(savedInstanceState)

        setAdapter(
                if (!isChecking)
                    ViewLayout.LIST_BASIC
                else
                    ViewLayout.LIST_CHECK, checkList
        )

        view?.onItemClickListener = this

        btnFun()
    }

    private fun btnFun() {
        select_all_btn.onClick {
            val tempArray = modAdapter.getIsSelected()
            for (i in 0..tempArray.size()-1) {
                modAdapter.notIsSelected(i)
            }
            runOnUiThread { modAdapter.notifyDataSetChanged() }
        }

        confirmBtn_fileman.onClick {
            //TODO
            toast(genCheckList())
        }

        cancelBtn_fileman.onClick {
            finish()
        }
    }

    private fun restoreState(savedInstanceState: Bundle?) {
        (application as ThisApplication).runOnBgWithCb(Runnable {
            if (savedInstanceState == null) {
                val path = intent.getStringExtra("path")
                ROOT = path ?: FileMan.ROOT
                tree.setRoot(tree.rootNodeFactory(ROOT))
                updateBundle(ROOT)
            } else {
                currentPath = savedInstanceState.getCharSequence("currentPath").toString()
                LogInstance.log("$this", currentPath, LogInstance.LogType.DEBUG, showLog)
                updateBundle(currentPath)
                isChecking = savedInstanceState.getCharSequence("listStatus") == true.toString()
            }
        }, this)
    }

    private fun initVar() {
        obj = (application as ThisApplication).fileApiFactory(this)
    }

    private fun initView() {
        setContentView(R.layout.file_man_view) //normal list view
        view = findViewById(R.id.file_man_list) as ListView
    }

    private fun genCheckList(): String {
        val buffer = StringBuffer()

        (application as ThisApplication).runOnBgAndJoin(Runnable {
            val tempArray = modAdapter.getIsSelected()

            for (i in 0..tempArray.size() - 1) {
                if (tempArray[i])
                    buffer.append(i).append(",")
            }

            if (buffer.length !== 0)
                buffer.deleteCharAt(buffer.length - 1)
            else
                buffer.append("No item is checked!")
        })

        return buffer.toString()
    }

    override fun onSaveInstanceState(outState: Bundle?) {
            outState?.putCharSequence("currentPath", currentPath)
            outState?.putCharSequence("listStatus", isChecking.toString())

            val src = modAdapter.getIsSelected()
            val temp = ShortArray(src.size())
            for (i in 0..src.size()-1) {
                temp[i] = if (src[i]) 1 else 0
            }
            outState?.putShortArray("checkList", temp)

            super.onSaveInstanceState(outState)
    }

    /***
     * Refresh the list
     *
     * Warning: MUST be run in UI thread
     * @param path Destination Directory
     * @see updateBundle
     */
    override fun renewList(path: String) {
        updateBundle(path)
        runOnUiThread { modAdapter.notifyDataSetChanged() }
        currentPath = path
        LogInstance.log("Current Path", currentPath, LogInstance.LogType.DEBUG, showLog)
    }

    /***
     * To update the list and map while destination directory changed
     * @param path Destination directory
     */
    override fun updateBundle(path: String) {
        (application as ThisApplication).runOnBgWithCb(Runnable {
            val _bundle = fMan.getDirMap(path, ROOT)
            tree.putAll(_bundle.getSerializable(MAP_TAG_ITEM) as ArrayList<String>,
                    _bundle.getSerializable(MAP_TAG_PATH) as Map<String, String>, path)
            showList.clear()
            showList.addAll(tree.toArrayList(path))
        }, this)
    }

    override fun changeDir(position: Int) {
        val path: String

        if (!showList[position].equals("../") && !showList[position].equals("/")) {
            path = tree.get((showList[position]).split("/")[0])?.path as String
        } else {
            path = when (showList[position]) {
                "../" -> tree.get(currentPath)?.parentPath as String
                "/" -> ROOT
                else -> throw Exception("Check$this")
            }
        }

        val file = File(path)

        if (file.isDirectory) {
            if (file.canRead()) {
                LogInstance.log("Renew List", path, LogInstance.LogType.DEBUG, showLog)
                renewList(path)
            } else {
                AlertDialog.Builder(this@LocalFileManActivity)
                        .setTitle("[" + file.name + "] folder can't be read!")
                        .setIcon(R.drawable.notification_template_icon_bg)
                        .setPositiveButton("OK", { dialogInterface, i -> })
                        .show()
            }
        } else {
            (application as ThisApplication).runOnBg(Runnable { obj.uploadFile(path) })
        }
    }

    override fun threadFinish() {
        runOnUiThread { modAdapter.notifyDataSetChanged() }
    }

}
